package com.bjpowernode.crm.settings.web.controller;

import com.bjpowernode.crm.commons.contants.Constants;
import com.bjpowernode.crm.commons.domain.ResultEntity;
import com.bjpowernode.crm.commons.utils.DateUtils;
import com.bjpowernode.crm.commons.utils.MD5Util;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 郭俊才
 * 2021/8/16
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    // 从首页跳转到登录页面
    @RequestMapping("/settings/qx/user/login.do")
    public String toLogin(HttpServletRequest request) {
        // 查看当前用户是否有cookie信息
        String loginAct = null;
        String loginPwd = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("loginAct".equals(cookie.getName())) {
                loginAct = cookie.getValue();
                continue;
            }
            if ("loginPwd".equals(cookie.getName())) {
                loginPwd = cookie.getValue();
            }
        }
        if (loginAct != null && loginPwd != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("loginAct", loginAct);
            map.put("loginPwd", MD5Util.getMD5(loginPwd));
            User user = userService.queryUserByLoginActAndPwd(map);
            if (user != null) {
                request.getSession().setAttribute(Constants.MESSAGE_SESSION_NAME, user);
                return "redirect:/workbench/index.do";
            }
        }
        return "settings/qx/user/login";
    }

    @RequestMapping(value = "/settings/qx/user/doLogin.do", method = RequestMethod.POST)
    @ResponseBody
    public ResultEntity doLogin(String loginAct, String loginPwd, String isRemPwd, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取用户登录的IP地址
        String ip = request.getRemoteAddr();
        System.out.println(ip);
        // 将密码转为md5加密
        String loginPwdForMD5 = MD5Util.getMD5(loginPwd);
        // 将账号和密码封装到map中
        Map<String, Object> map = new HashMap<>();
        map.put("loginAct", loginAct);
        map.put("loginPwd", loginPwdForMD5);
        // 从数据库中查找用户信息
        User user = userService.queryUserByLoginActAndPwd(map);


        // 没有cookie，判断用户是否存在
        if (user == null) {
            return ResultEntity.failed("用户名或密码错误");
        } else {
            //1.比较用户的超时时间,登录状态，ip地址
            if (DateUtils.formatDateTime(new Date()).compareTo(user.getExpireTime()) > 0) {
                return ResultEntity.failed("登录超时");
            } else if (Constants.FAILED_CODE.equals(user.getLockState())) {
                return ResultEntity.failed("账号锁定");
            } else if (!user.getAllowIps().contains(ip)) {
                return ResultEntity.failed("ip受限");
            } else {
                // 十天内免登录
                // 1.判断isRemPwd是否选中,进行cookie的创建
                if ("true".equals(isRemPwd)) {
                    Cookie cookie1 = new Cookie("loginAct", loginAct);
                    Cookie cookie2 = new Cookie("loginPwd", loginPwd);
                    cookie1.setMaxAge(10 * 24 * 60 * 60);
                    cookie2.setMaxAge(10 * 24 * 60 * 60);
                    response.addCookie(cookie1);
                    response.addCookie(cookie2);
                }
                // 将登录后的用户信息放到session域中
                session.setAttribute(Constants.MESSAGE_SESSION_NAME, user);
                return ResultEntity.successWithData(user);
            }

        }
    }

    @RequestMapping("/settings/qx/user/logout.do")
    public String loginOut(HttpServletResponse response,HttpSession session) {
        //清除cookie
        Cookie cookie1 = new Cookie("loginAct", null);
        Cookie cookie2 = new Cookie("loginPwd", null);
        cookie1.setMaxAge(0);
        cookie2.setMaxAge(0);
        response.addCookie(cookie1);
        response.addCookie(cookie2);
        //清除session
        session.invalidate();
        return "redirect:/settings/qx/user/login";
    }

}
